﻿#coding:utf-8
from pandas import DataFrame 
from xlrd import open_workbook
from re import findall
from EzSymlink import conf
from os import path,makedirs,listdir
import json
import time
def wast_time(func):
	def inner(self):
		start_time = time.time()
		v = func(self)
		end_tim = time.time()
		print("程序完成，用时%.3f秒\n"%(end_tim - start_time))
		return v
	return inner

class Sl_Tools:

	def __init__(self):
		self.f_path=conf.f_path
		self.sheets=conf.exc_obj["exec_items"]["sheets"]
		self.driver_parse=conf.driver_parse
		self.datatype_parse=conf.datatype_parse
		if not path.exists(self.f_path["symlink_cj"]):makedirs(self.f_path["symlink_cj"])
		if not path.exists(self.f_path["symlink_zf"]): makedirs(self.f_path["symlink_zf"])
		if not path.exists(self.f_path["zjq"]): makedirs(self.f_path["zjq"])
		try:
			self.db_xls=open_workbook(self.f_path["db_xls"], formatting_info=True)
		except Exception as e:
			print("未能打开点表文件，请检查设置,错误信息：")
			print(e)
			quit()
		if not self.sheets:
			self.sheets=self.db_xls.sheet_names()
		print("\n","-"*50,"\n\t初始化正常，打开文件 " + self.f_path["db_xls"] + " 成功\n","-"*50,"\n")

	def main_cycle(self):
		print("===" * 10, "主程序开始", "===" * 10)
		for sheet_name in self.sheets:
				sheet=self.db_xls.sheet_by_name(sheet_name)
				print("\t打开表格 "+sheet_name+" 成功")
				row_num = sheet.nrows
				# col_num=sheet.ncols
				self.boolid=0
				self.intgid=0
				table_data = {"devices":None,"driver_name":None,"table_name":None}
				tag_data = {"tag_id":None,"jc_addr":None,"data_type":None,"mod_type":None,"tag_name":None,"tag_des":None,"res_des":None,"alm_args":None,"taghead":None}
				table_data["devices"]=str(sheet.cell_value(0, 4))
				table_data["driver_name"]=str(sheet.cell_value(0,1))
				table_data["table_name"]= str(sheet.cell_value(0, 5))
				try:
					if "："in table_data["table_name"]:
						table_data["table_name"]=table_data["table_name"].split("：")[1]
					if "：" in table_data["devices"]:
						table_data["devices"] = table_data["devices"].split("：")[1]
					if "：" in table_data["driver_name"]:
						table_data["driver_name"] = table_data["driver_name"].split("：")[1]
					table_data["devices"]=json.loads(table_data["devices"])
				except Exception as e:
					print("可能第一行数据格式不对")
					print(e)
					continue
				for driver_key, driver_value in self.driver_parse.items():
					if table_data["driver_name"] in driver_value:
						table_data["driver_name"] = driver_key
						break
				else:
					print("驱动未开发或者驱动输入错误，请检查")
				self.boolid=0 #bool类型id
				self.intgid=0 #非布尔类型id
				for device_name in table_data["devices"].keys():
					self.Data_symlink_cj = {
						"点来源": [], "完整名称": [], "通道类型": [], "描述": [], "类型": [], "标记": [], "权限": [], "采集周期(ms)": [],
						"IO.n[0]": [], "IO.n[1]": [], "IO.n[2]": [], "IO.n[3]": [], "IO.n[4]": [], "IO.n[5]": [],
						"IO.n[6]": [],
						"IO.n[7]": [], "IO.n[8]": [], "IO.n[9]": [], "IO.n[10]": [], "IO.n[11]": [],
						"IO.csData[0]": [], "IO.csData[1]": [], "IO.csData[2]": [], "IO.csData[3]": [],
						"IO.csData[4]": [], "IO.csData[5]": [],
						"opc_vtDataType": [], "opc_csItemID": [], "opc_csAccessPath": [],
						"IoLinker.m_nKind": [], "IoLinker.m_nMode": [], "IoLinker.m_csObject": [],
						"IoLinker.m_csPath": [],
						"模拟量额定值": [], "模拟量初始值": [], "模拟量取绝对值": [], "模拟量CT/PT": [], "模拟量系数": [], "模拟量倍率系数": [],
						"模拟量基数": [], "模拟量基础倍率": [], "模拟量量程变换": [],
						"模拟量裸数据上限": [], "模拟量裸数据下限": [], "模拟量量程上限": [], "模拟量量程下限": [],
						"数字量初始值": [], "数字量采集取反": [], "数字量真值描述": [], "数字量假值描述": []
					}
					self.Data_symlink_zf = {"点来源": [], "完整名称": [], "描述": [], "数据库关联": [], "变化通知": [], "权限": [], "扫描周期(ms)": [],
							"计算": [],
							"基数": [], "倍率": [], "DS.n[0]": [], "DS.n[1]": [], "DS.n[2]": [], "DS.n[3]": [],
							"DS.n[4]": [], "DS.n[5]": [], "DS.n[6]": [],
							"DS.n[7]": [], "DS.n[8]": [], "DS.n[9]": [], "DS.n[10]": [], "DS.n[11]": [],
							"DS.csData[0]": [], "DS.csData[1]": [], "DS.csData[2]": [],
							"DS.csData[3]": [], "DS.csData[4]": [], "DS.csData[5]": []}
					self.Data_symlink_zf_new = {";序号": [], "名称": [], "描述": [], "方向": [], "变化通知": [], "连接字符串": [], "扫描周期(ms)": [],
							"系数运算": [], "系数基数": [], "系数倍率": [], "功能区": [], "地址": [], "格式": [], "位偏移": []}
					self.Data_zjq_intg = {"NAME": [], "KIND": [], "DESC": [], "UNIT": [], "FORMAT": [], "LASTPV": [], "PV": [],
							"EU": [],
							"EULO": [], "EUHI": [], "PVRAW": [], "SCALEFL": [], "OVERCUT": [], "PVRAWLO": [],
							"PVRAWHI": [], "STATIS": [], "ALMENAB": [],
							"DEADBAND": [], "LL": [], "LO": [], "HI": [], "HH": [], "RATE": [], "DEV": [], "LLPR": [],
							"LOPR": [], "HIPR": [], "HHPR": [], "RATEPR": [], "DEVPR": [], "RATECYC": [], "SP": [],
							"SQRTFL": [],
							"ALARMDELAY": [], "LINEFL": [], "LINETBL": [], "SEN": [], "SECU": [], "ROCFL": [],
							"ROC": [],
							"HisKind": [], "HisValue": [], "LinkKind": [], "LinkDev": [], "LinkDesc": [], "LinkStr": [],
							"Linkn0": [], "Linkn1": [], "Linkn2": [], "Linkn3": [], "Linkn4": [], "Linkn5": [],
							"Linkn6": [],
							"LinkFmt": [], "LinkBit": [], "LinkVer": [], "LinkFlag": [], "LinkValue": []}
					self.Data_zjq_bool = {"NAME": [], "KIND": [], "DESC": [], "UNIT": [], "PV": [], "OFFMES": [],
							 "ONMES": [], "ALMENAB": [], "NORMALVAL": [], "ALARMPR": [], "SECU": [], "ALARMDELAY": [],
							 "HisKind": [], "HisValue": [], "LinkKind": [], "LinkDev": [], "LinkDesc": [],
							 "LinkStr": [],
							 "Linkn0": [], "Linkn1": [], "Linkn2": [], "Linkn3": [], "Linkn4": [], "Linkn5": [],
							 "Linkn6": [],
							 "LinkFmt": [], "LinkBit": [], "LinkVer": [], "LinkFlag": [], "LinkValue": []}

					for row_now in range(row_num):
						if row_now<2:
							continue
						tag_data["tag_id"]=str(sheet.cell_value(row_now,0)).replace(" ","").replace("\n","").replace(".0","")
						tag_data["jc_addr"]=str(sheet.cell_value(row_now,1)).replace(" ","").replace("\n","").replace("VD","V").replace("VS","V").replace("VW","V")
						tag_data["data_type"]=str(sheet.cell_value(row_now,2))
						tag_data["mod_type"]=str(sheet.cell_value(row_now,3))
						tag_data["tag_name"]=str(sheet.cell_value(row_now,4)).replace(" ","").replace("\n","").replace("/","-").replace(".","")
						tag_data["tag_des"]=str(sheet.cell_value(row_now,5)).replace(" ","_").replace("\n","").replace(",","_")
						tag_data["res_des"]=str(sheet.cell_value(row_now,6)).replace(" ","").replace("\n","")
						jc_color=self.db_xls.xf_list[sheet.cell_xf_index(row_now, 0)].background.pattern_colour_index
						tag_color = self.db_xls.xf_list[sheet.cell_xf_index(row_now, 4)].background.pattern_colour_index
						if jc_color!=50 and tag_color!=50:continue
						tag_head=""
						#判断是否有中文，并且替换
						res=findall("[\u4e00-\u9fa5]+",tag_data["tag_name"])
						res2=findall("[a-zA-Z]+",tag_data["jc_addr"])
						res3 = findall("\$\{(.+?)\}", tag_data["res_des"])
						if res3:
							self.jcxs = 1
							self.jcbl = res2[0].replace("${", "").replace("}", "").split("+")[1].split("*")[0]
							self.jcjs = res2[0].replace("${", "").replace("}", "").split("+")[0]
						else:
							self.jcxs = 0
							self.jcbl = 0
							self.jcjs = 0
						if res2:
							tag_data["tag_head"]=findall("[a-zA-Z]+",tag_data["jc_addr"])[0]	#寄存器头,做判断用
						if tag_data["tag_des"].strip() == "":
							tag_data["tag_des"] = tag_data["tag_name"]
						if res or tag_data["tag_name"].strip()=="":
							tag_data["tag_des"]=tag_data["tag_des"]+""+tag_data["tag_name"]
							tag_data["tag_name"]="hans"+"_"+str(tag_data["tag_id"])
						elif len(tag_data["tag_name"])>13:
							tag_data["tag_name"]="n2l_"+device_name+"_"+str(tag_data["tag_id"])
						if table_data["driver_name"]=="modbus":
							if tag_data["mod_type"]=="1" or tag_data["mod_type"]=="3":
								tag_data["tag_head"]="RO"
							elif tag_data["mod_type"]=="2" or tag_data["mod_type"]=="4":
								tag_data["tag_head"]="RW"
						for datatype_key,datatype_value in self.datatype_parse.items():
							if tag_data["data_type"] in datatype_value:
								tag_data["data_type"]=datatype_key
								break
						else:
							print(tag_data["tag_name"])
							print("有数据类型对应不上："+tag_data["data_type"])
						self.dsn0 = 0
						self.dsn1 = 0
						self.dsn2 = 0
						boolkd=0
						intgkd=0
						if tag_data["data_type"] == '布尔':
							self.dsn0 = 0
							self.dsn1 = self.boolid
							boolkd=1
							self.dsn2 = -1
							self.typedes = "BOOL"
							self.typeid = 0
						elif tag_data["data_type"] == '有符号单字':
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 1
							self.dsn2 = 0
							self.typedes = "short"
							self.typeid = 3
						elif tag_data["data_type"] == '无符号单字':
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 1
							self.dsn2 = 1
							self.typedes = "WORD"
							self.typeid = 4
						elif tag_data["data_type"] == '有符号双字':
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 2
							self.dsn2 = 3
							self.typedes = "long"
							self.typeid = 6
						elif tag_data["data_type"] == '无符号双字':
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 2
							self.dsn2 = 5
							self.typedes = "DWORD"
							self.typeid = 7
						elif tag_data["data_type"] == "单精度浮点":
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 2
							self.dsn2 = 7
							self.typedes = "float"
							self.typeid = 9
						elif tag_data["data_type"] == '双精度浮点':
							self.dsn0 = 2
							self.dsn1 = self.intgid
							intgkd = 4
							self.dsn2 = 8
							self.typedes = "double"
							self.typeid = 10
						self.symlink_cj(tag_data,table_data,device_name)
						self.symlink_zf(tag_data,table_data,device_name)
						self.symlink_zf_new(tag_data, table_data, device_name)
						self.zjq(tag_data, table_data, device_name)
						self.intgid=self.intgid+intgkd
						self.boolid=self.boolid+boolkd
					dataframe = DataFrame(self.Data_symlink_cj)
					dataframe.to_csv(conf.f_path["symlink_cj"] + sheet_name + "_" + device_name + "_采集.csv",
									 index=False, sep=',', encoding='gbk')  # utf_8_sig
					dataframe = DataFrame(self.Data_symlink_zf)
					dataframe.to_csv(conf.f_path["symlink_zf"] + sheet_name + "_" + device_name + "_转发.csv",
									 index=False, sep=',', encoding='gbk')  # utf_8_sig
					dataframe = DataFrame(self.Data_symlink_zf_new)
					dataframe.to_csv(conf.f_path["symlink_zf"] + sheet_name + "_" + device_name + "_转发新.csv",
									 index=False, sep=',', encoding='gbk')  # utf_8_sig
					dataframe = DataFrame(self.Data_zjq_intg)
					dataframe = dataframe.replace(",", "	")
					dataframe.to_csv(self.f_path["zjq"] + sheet_name + "_Intg.txt", index=False, sep='\t',
									 encoding='gbk')  # utf_8_sig
					dataframe = DataFrame(self.Data_zjq_bool)
					dataframe.to_csv(self.f_path["zjq"] + sheet_name + "_Bool.txt", index=False, sep='\t',
									 encoding='gbk')  # utf_8_sig
					print("--" * 10, "完成设备", sheet_name, "--" * 10)
					print("===" * 10, "主程序结束", "===" * 10, "")



	def symlink_cj(self,tag_data,table_data,device_name):
		ion0 = 0
		ion1 = 0
		ion2 = 0
		ion3 = 0
		ion4 = 0
		if table_data["driver_name"]=="西门子/s7-200":
			if tag_data["tag_head"]=="M":
				ion0=0
				ion2=0
				if ":" in tag_data["jc_addr"]:
					ion3=tag_data["jc_addr"][1:].split(':')[1]
					ion1=tag_data["jc_addr"][1:].split(':')[0]
				elif "." in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"][1:].split('.')[0]
					ion3=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="I":
				ion0=1
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion3=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="Q":
				ion0=2
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion3=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="V":
				ion0=5
				ion1=tag_data["jc_addr"][1:]
				ion3=0
				if "." in tag_data["jc_addr"][1:]:
					ion1=tag_data["jc_addr"][1:].split(".")[0]
					ion3=tag_data["jc_addr"][1:].split(".")[1]
				elif ":" in tag_data["jc_addr"][1:]:
					ion1=tag_data["jc_addr"][1:].split(":")[0]
					ion3=tag_data["jc_addr"][1:].split(":")[1]
			elif tag_data["tag_head"]=="S":
				ion0=5
				ion1=tag_data["jc_addr"][1:]
				ion3=0
			elif tag_data["tag_head"]=="T":
				ion0=3
				ion1=tag_data["jc_addr"][1:]
				ion3=0
			elif tag_data["tag_head"]=="C":
				ion0=4
				ion1=tag_data["jc_addr"][1:]
				ion3=0


			if tag_data["data_type"]=="布尔":
				ion2=0
				if ":" in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"][1:].split(":")[0]
					ion3=tag_data["jc_addr"][1:].split(":")[1]
				elif "." in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"][1:].split(".")[0]
					ion3=tag_data["jc_addr"][1:].split(".")[1]
			elif tag_data["data_type"]=="无符号单字节" :
				ion2=1
			elif tag_data["data_type"]=="有符号单字节":
				ion2=2
			elif tag_data["data_type"]=="无符号单字":
				ion2=3
			elif tag_data["data_type"]=="有符号单字":
				ion2=4
			elif tag_data["data_type"]=="无符号双字":
				ion2=5
			elif tag_data["data_type"]=="有符号双字":
				ion2=6
			elif tag_data["data_type"]=="单精度浮点":
				ion2=7
			elif tag_data["data_type"]=="字符串":

				ion2=8

		elif table_data["driver_name"]=="西门子/s7-300":
			if tag_data["tag_head"]=="M":
				ion0=2
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion2=0
				ion4=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="I":
				ion0=0
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion2=0
				ion4=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="Q":
				ion0=1
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion2=0
				ion4=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="DB":
				if "," in tag_data["jc_addr"]:
					jc_addr=tag_data["jc_addr"].replace("D","").replace("B","").replace("W","").replace("X","")
					kdz = tag_data["jc_addr"].split(",")[0]
					pyw=tag_data["jc_addr"].split(",")[1]
				else:
					kdz=tag_data["jc_addr"].split("[")[1].split("]")[0]
					pyw=tag_data["jc_addr"].split("]")[1]
				wdz="0"
				if ":" in tag_data["jc_addr"]:
					wdz = pyw.split(":")[1]
					pyw=pyw.split(":")[0]
				elif "." in tag_data["jc_addr"]:
					wdz = pyw.split(".")[1]
					pyw=pyw.split(".")[0]
				ion0=3
				ion1=pyw
				ion2=kdz
				ion4=wdz
			elif tag_data["tag_head"]=="PIW":
				ion0=6
				ion1=tag_data["jc_addr"][3:]
				ion2=0
				ion4=0

			if tag_data["data_type"]=="布尔":
				ion3=0
			elif tag_data["data_type"]=="无符号单字节" :
				ion3=1
			elif tag_data["data_type"]=="有符号单字节":
				ion3=2
			elif tag_data["data_type"]=="无符号单字":
				ion3=3
			elif tag_data["data_type"]=="有符号单字":
				ion3=4
			elif tag_data["data_type"]=="无符号双字":
				ion3=5
			elif tag_data["data_type"]=="有符号双字":
				ion3=6
			elif tag_data["data_type"]=="单精度浮点":
				ion3=7
			elif tag_data["data_type"]=="字符串":
				ion3=8

		elif table_data["driver_name"]=="西门子/s7-1200":
			if tag_data["tag_head"]=="M":
				ion0=2
				if "." in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"][1:].split('.')[0]
					ion2=0
					ion4=tag_data["jc_addr"][1:].split('.')[1]
				elif ":" in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"][1:].split(':')[0]
					ion2=0
					ion4=tag_data["jc_addr"][1:].split(':')[1]
				else:
					ion1=tag_data["jc_addr"][1:]
					ion2=0
					ion4=0
			elif tag_data["tag_head"]=="I":
				ion0=0
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion2=0
				ion4=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="Q":
				ion0=1
				ion1=tag_data["jc_addr"][1:].split('.')[0]
				ion2=0
				ion4=tag_data["jc_addr"][1:].split('.')[1]
			elif tag_data["tag_head"]=="DB":
				#if jcaddr!="DB[22]0.3":continue
				if "," in tag_data["jc_addr"]:
					jc_addr = tag_data["jc_addr"].replace("D", "").replace("B", "").replace("W", "").replace("X", "")
					kdz = jc_addr.split(",")[0]
					pyw = jc_addr.split(",")[1]
				else:
					kdz=tag_data["jc_addr"].split("[")[1].split("]")[0]
					pyw=tag_data["jc_addr"].split("]")[1]
				wdz="0"
				if ":" in tag_data["jc_addr"]:
					wdz=pyw.split(":")[1]
					pyw=pyw.split(":")[0]
				elif "." in tag_data["jc_addr"]:
					#print(jc_addr)
					wdz=pyw.split(".")[1]
					pyw=pyw.split(".")[0]
				ion0=3
				ion1=pyw
				ion2=kdz
				ion4=wdz
			elif tag_data["tag_head"]=="PIW":
				ion0=6
				ion1=tag_data["jc_addr"][3:]
				ion2=0
				ion4=0

			if tag_data["data_type"]=="布尔":
				ion3=0
			elif tag_data["data_type"]=="无符号单字节" :
				ion3=1
			elif tag_data["data_type"]=="有符号单字节":
				ion3=2
			elif tag_data["data_type"]=="无符号单字":
				ion3=3
			elif tag_data["data_type"]=="有符号单字":
				ion3=4
			elif tag_data["data_type"]=="无符号双字":
				ion3=5
			elif tag_data["data_type"]=="有符号双字":
				ion3=6
			elif tag_data["data_type"]=="单精度浮点":
				ion3=7
			elif tag_data["data_type"]=="字符串":
				ion3=8

		elif table_data["driver_name"]=="三菱/Q系列":
				if tag_data["tag_head"]=="M":
					ion0=144
					ion1=tag_data["jc_addr"][2:]
					ion3=0
				elif tag_data["tag_head"]=="X":
					ion0=156
					ion1=tag_data["jc_addr"][2:]
					ion3=0
				elif tag_data["tag_head"]=="Y":
					ion0=157
					ion1=tag_data["jc_addr"][2:]
					ion3=0
				elif tag_data["tag_head"]=="D":
					ion0=168
					ion1=tag_data["jc_addr"][2:]
					ion3=0
					if ":" in tag_data["jc_addr"]:
						ion1=tag_data["jc_addr"][2:].split(":")[0]
						ion3=tag_data["jc_addr"][2:].split(":")[1]
					elif "." in tag_data["jc_addr"]:
						ion1=tag_data["jc_addr"][2:].split(".")[0]
						ion3=tag_data["jc_addr"][2:].split(".")[1]
				if tag_data["data_type"]=="布尔":
					ion2=0
				elif tag_data["data_type"]=="无符号单字":
					ion2=1
				elif tag_data["data_type"]=="有符号单字":
					ion2=2
				elif tag_data["data_type"]=="无符号双字":
					ion2=3
				elif tag_data["data_type"]=="有符号双字":
					ion2=4
				elif tag_data["data_type"]=="单精度浮点":
					ion2=5
				elif tag_data["data_type"]=="双精度浮点":
					ion2=6
		elif table_data["driver_name"]=="modbus":
			mod_type=tag_data["mod_type"].strip()
			if mod_type=='1':
				ion0=0
				ion1=tag_data["jc_addr"]
				tag_head="RO"
			if mod_type=='2':
				ion0=1
				ion1=tag_data["jc_addr"]
				tag_head="WO"
			elif mod_type=='3':
				ion0=2
				ion1=tag_data["jc_addr"]
				tag_head="RO"
				ion3=0
				ion4=-1
			elif mod_type=='4':
				ion0=3
				ion1=tag_data["jc_addr"]
				tag_head="RO"
				ion3=0
				ion4=-1
			elif mod_type=='5':
				ion0=4
				ion1=tag_data["jc_addr"]
				tag_head="WO"
				ion3=0
				ion4=-1
			elif mod_type=='6':
				ion0=5
				ion1=tag_data["jc_addr"]
				tag_head="WO"
				ion3=0
				ion4=-1
			elif mod_type == '1,5':
				ion0 = 0
				ion1 = tag_data["jc_addr"]
				tag_head = "RW"
				ion3 = 0
				ion4 = -1
			elif mod_type == '3,6':
				ion0 = 2
				ion1 = tag_data["jc_addr"]
				tag_head = "RW"
				ion3 = 0
				ion4 = -1
				if "-" in tag_data["jc_addr"]:
					jc_addr=tag_data["jc_addr"].split("-")[0]
				if "." in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"].split(".")[0]
					ion3=tag_data["jc_addr"].split(".")[1]
				elif ":" in tag_data["jc_addr"]:
					ion1=tag_data["jc_addr"].split(":")[0]
					ion3=tag_data["jc_addr"].split(":")[1]
			if tag_data["data_type"]=="布尔":
				ion2=-1
			elif tag_data["data_type"]=="无符号单字":
				ion2=1
			elif tag_data["data_type"]=="有符号单字":
				ion2=2
			elif tag_data["data_type"]=="无符号双字":
				ion2=5
			elif tag_data["data_type"]=="有符号双字":
				ion2=8
			elif tag_data["data_type"]=="单精度浮点":
				ion2=13
			elif tag_data["data_type"]=="双精度浮点":
				ion2=29
			else:
				ion2=0

		self.Data_symlink_cj["点来源"].append("3")
		self.Data_symlink_cj["完整名称"].append(table_data["table_name"]+"."+device_name+"."+tag_data["tag_head"]+"."+tag_data["tag_name"])
		self.Data_symlink_cj["通道类型"].append("0")
		self.Data_symlink_cj["描述"].append(tag_data["tag_des"])
		self.Data_symlink_cj["类型"].append("1")
		self.Data_symlink_cj["标记"].append("0")
		self.Data_symlink_cj["权限"].append("0")
		self.Data_symlink_cj["采集周期(ms)"].append("1000")
		self.Data_symlink_cj["IO.n[0]"].append(ion0)
		self.Data_symlink_cj["IO.n[1]"].append(ion1)
		self.Data_symlink_cj["IO.n[2]"].append(ion2)
		self.Data_symlink_cj["IO.n[3]"].append(ion3)
		self.Data_symlink_cj["IO.n[4]"].append(ion4)
		self.Data_symlink_cj["IO.n[5]"].append("0")
		self.Data_symlink_cj["IO.n[6]"].append("0")
		self.Data_symlink_cj["IO.n[7]"].append("0")
		self.Data_symlink_cj["IO.n[8]"].append("0")
		self.Data_symlink_cj["IO.n[9]"].append("0")
		self.Data_symlink_cj["IO.n[10]"].append("0")
		self.Data_symlink_cj["IO.n[11]"].append("0")
		self.Data_symlink_cj["IO.csData[0]"].append("")
		self.Data_symlink_cj["IO.csData[1]"].append("")
		self.Data_symlink_cj["IO.csData[2]"].append("")
		self.Data_symlink_cj["IO.csData[3]"].append("")
		self.Data_symlink_cj["IO.csData[4]"].append("")
		self.Data_symlink_cj["IO.csData[5]"].append("")
		self.Data_symlink_cj["opc_vtDataType"].append("0")
		self.Data_symlink_cj["opc_csItemID"].append("")
		self.Data_symlink_cj["opc_csAccessPath"].append("")
		self.Data_symlink_cj["IoLinker.m_nKind"].append("0")
		self.Data_symlink_cj["IoLinker.m_nMode"].append("0")
		self.Data_symlink_cj["IoLinker.m_csObject"].append("")
		self.Data_symlink_cj["IoLinker.m_csPath"].append("")
		self.Data_symlink_cj["模拟量额定值"].append("0")
		self.Data_symlink_cj["模拟量初始值"].append("0")
		self.Data_symlink_cj["模拟量取绝对值"].append("0")
		self.Data_symlink_cj["模拟量CT/PT"].append("0")
		self.Data_symlink_cj["模拟量系数"].append(0)
		self.Data_symlink_cj["模拟量倍率系数"].append("0")
		self.Data_symlink_cj["模拟量基数"].append(0)
		self.Data_symlink_cj["模拟量基础倍率"].append(0)
		self.Data_symlink_cj["模拟量量程变换"].append("0")
		self.Data_symlink_cj["模拟量裸数据上限"].append("100")
		self.Data_symlink_cj["模拟量裸数据下限"].append("0")
		self.Data_symlink_cj["模拟量量程上限"].append("1000")
		self.Data_symlink_cj["模拟量量程下限"].append("0")
		self.Data_symlink_cj["数字量初始值"].append("")
		self.Data_symlink_cj["数字量采集取反"].append("")
		self.Data_symlink_cj["数字量真值描述"].append("")
		self.Data_symlink_cj["数字量假值描述"].append("")


	def symlink_zf(self,tag_data,table_data,device_name):
		self.Data_symlink_zf["点来源"].append("2")
		self.Data_symlink_zf["完整名称"].append(tag_data["tag_head"]+"."+tag_data["tag_name"])
		self.Data_symlink_zf["描述"].append(tag_data["tag_des"])
		self.Data_symlink_zf["数据库关联"].append("db."+table_data["table_name"]+"."+device_name+"."+tag_data["tag_head"]+"."+tag_data["tag_name"])
		self.Data_symlink_zf["变化通知"].append("0")
		self.Data_symlink_zf["权限"].append("2")
		self.Data_symlink_zf["扫描周期(ms)"].append("1000")
		self.Data_symlink_zf["计算"].append(self.jcxs)
		self.Data_symlink_zf["基数"].append(self.jcjs)
		self.Data_symlink_zf["倍率"].append(self.jcbl)
		self.Data_symlink_zf["DS.n[0]"].append(self.dsn0)
		self.Data_symlink_zf["DS.n[1]"].append(self.dsn1)
		self.Data_symlink_zf["DS.n[2]"].append(self.dsn2)
		self.Data_symlink_zf["DS.n[3]"].append("0")
		self.Data_symlink_zf["DS.n[4]"].append("0")
		self.Data_symlink_zf["DS.n[5]"].append("0")
		self.Data_symlink_zf["DS.n[6]"].append("0")
		self.Data_symlink_zf["DS.n[7]"].append("0")
		self.Data_symlink_zf["DS.n[8]"].append("0")
		self.Data_symlink_zf["DS.n[9]"].append("0")
		self.Data_symlink_zf["DS.n[10]"].append("0")
		self.Data_symlink_zf["DS.n[11]"].append("0")
		self.Data_symlink_zf["DS.csData[0]"].append("")
		self.Data_symlink_zf["DS.csData[1]"].append("")
		self.Data_symlink_zf["DS.csData[2]"].append("")
		self.Data_symlink_zf["DS.csData[3]"].append("")
		self.Data_symlink_zf["DS.csData[4]"].append("")
		self.Data_symlink_zf["DS.csData[5]"].append("")




	def symlink_zf_new(self,tag_data,table_data,device_name):
		self.Data_symlink_zf_new[";序号"].append(tag_data["tag_id"])
		self.Data_symlink_zf_new["名称"].append(tag_data["tag_name"])
		self.Data_symlink_zf_new["描述"].append(tag_data["tag_des"])
		self.Data_symlink_zf_new["方向"].append(0)
		self.Data_symlink_zf_new["变化通知"].append(0)
		self.Data_symlink_zf_new["连接字符串"].append("db." + table_data["table_name"] + "." + device_name + "." + tag_data["tag_head"] + "." + tag_data["tag_name"])
		self.Data_symlink_zf_new["扫描周期(ms)"].append(1000)
		self.Data_symlink_zf_new["系数运算"].append(self.jcxs)
		self.Data_symlink_zf_new["系数基数"].append(self.jcjs)
		self.Data_symlink_zf_new["系数倍率"].append(self.jcbl)
		self.Data_symlink_zf_new["功能区"].append(self.dsn0)
		self.Data_symlink_zf_new["地址"].append(self.dsn1)
		self.Data_symlink_zf_new["格式"].append(self.dsn2)
		self.Data_symlink_zf_new["位偏移"].append(0)





	def zjq(self,tag_data, table_data, device_name):
					if tag_data["alm_args"]:
							tag_data["alm_args"]=json.loads(tag_data["alm_args"])
							try:
								tag_data["alm_args"].get(1)
							except:
								print("tagid为",tag_data["tag_id"],"行报警参数错误")
					else:
						tag_data["alm_args"]={}
					ALMENAB = 0		#"报警开启状态"
					NORMALVAL=0		#"报警初始值"
					ALARMDELAY=0	#"报警延迟"
					ALARMPR=3		#"报警优先级"
					LL=0
					LO=10
					HI=90
					HH=100
					if tag_data["alm_args"]:
						if tag_data["alm_args"].get("状态"):
							ALMENAB=tag_data["alm_args"]["状态"]
						if tag_data["alm_args"].get("初始值"):
							NORMALVAL=tag_data["alm_args"]["初始值"]
						if tag_data["alm_args"].get("延迟"):
							ALARMDELAY=tag_data["alm_args"]["延迟"]
						if tag_data["alm_args"].get("优先级"):
							ALARMPR=tag_data["alm_args"]["优先级"]
						if tag_data["alm_args"].get("上下限"):
							if tag_data["alm_args"]["上下限"].get("LL"):
								LL=tag_data["alm_args"]["上下限"]["LL"]
							if tag_data["alm_args"]["上下限"].get("LO"):
								LO = tag_data["alm_args"]["上下限"]["LO"]
							if tag_data["alm_args"]["上下限"].get("HI"):
								HI = tag_data["alm_args"]["上下限"]["HI"]
							if tag_data["alm_args"]["上下限"].get("HH"):
								HH = tag_data["alm_args"]["上下限"]["HH"]

					if tag_data["data_type"]!=  '布尔':
						self.Data_zjq_intg["NAME"].append(table_data["table_name"]+"_"+tag_data["tag_name"])
						self.Data_zjq_intg["KIND"].append(0)
						self.Data_zjq_intg["DESC"].append(tag_data["tag_des"])
						self.Data_zjq_intg["UNIT"].append(0)
						self.Data_zjq_intg["FORMAT"].append(3)
						self.Data_zjq_intg["LASTPV"].append(0)
						self.Data_zjq_intg["PV"].append(0)
						self.Data_zjq_intg["EU"].append("")
						self.Data_zjq_intg["EULO"].append(0)
						self.Data_zjq_intg["EUHI"].append(100)
						self.Data_zjq_intg["PVRAW"].append(0)
						self.Data_zjq_intg["SCALEFL"].append(0)
						self.Data_zjq_intg["OVERCUT"].append(0)
						self.Data_zjq_intg["PVRAWLO"].append(0)
						self.Data_zjq_intg["PVRAWHI"].append(4096)
						self.Data_zjq_intg["STATIS"].append(0)
						self.Data_zjq_intg["ALMENAB"].append(ALMENAB)
						self.Data_zjq_intg["DEADBAND"].append(0)
						self.Data_zjq_intg["LL"].append(LL)
						self.Data_zjq_intg["LO"].append(LO)
						self.Data_zjq_intg["HI"].append(HI)
						self.Data_zjq_intg["HH"].append(HH)
						self.Data_zjq_intg["RATE"].append(20)
						self.Data_zjq_intg["DEV"].append(20)
						self.Data_zjq_intg["LLPR"].append(3)
						self.Data_zjq_intg["LOPR"].append(3)
						self.Data_zjq_intg["HIPR"].append(3)
						self.Data_zjq_intg["HHPR"].append(3)
						self.Data_zjq_intg["RATEPR"].append(0)
						self.Data_zjq_intg["DEVPR"].append(0)
						self.Data_zjq_intg["RATECYC"].append(1)
						self.Data_zjq_intg["SP"].append(0)
						self.Data_zjq_intg["SQRTFL"].append(0)
						self.Data_zjq_intg["ALARMDELAY"].append(ALARMDELAY)
						self.Data_zjq_intg["LINEFL"].append(0)
						self.Data_zjq_intg["LINETBL"].append("")
						self.Data_zjq_intg["SEN"].append(0)
						self.Data_zjq_intg["SECU"].append(0)
						self.Data_zjq_intg["ROCFL"].append(0)
						self.Data_zjq_intg["ROC"].append(100)
						self.Data_zjq_intg["HisKind"].append(0)
						self.Data_zjq_intg["HisValue"].append(1)
						self.Data_zjq_intg["LinkKind"].append(0)
						self.Data_zjq_intg["LinkDev"].append(table_data["table_name"])
						self.Data_zjq_intg["LinkDesc"].append("HR Address:"+str(self.intgid)+" DataType:"+self.typedes)
						self.Data_zjq_intg["LinkStr"].append("HR Address:"+str(self.intgid)+" DataType:"+self.typedes)
						self.Data_zjq_intg["Linkn0"].append(2)
						self.Data_zjq_intg["Linkn1"].append(self.intgid)
						self.Data_zjq_intg["Linkn2"].append(self.typeid)
						self.Data_zjq_intg["Linkn3"].append(0)
						self.Data_zjq_intg["Linkn4"].append(-1)
						self.Data_zjq_intg["Linkn5"].append(0)
						self.Data_zjq_intg["Linkn6"].append(0)
						self.Data_zjq_intg["LinkFmt"].append(0)
						self.Data_zjq_intg["LinkBit"].append(0)
						self.Data_zjq_intg["LinkVer"].append(1)
						self.Data_zjq_intg["LinkFlag"].append(0)
						self.Data_zjq_intg["LinkValue"].append(0)
					else:
						self.Data_zjq_bool["NAME"].append(table_data["table_name"]+"_"+tag_data["tag_name"])
						self.Data_zjq_bool["KIND"].append(1)
						self.Data_zjq_bool["DESC"].append(tag_data["tag_des"])
						self.Data_zjq_bool["UNIT"].append(0)
						self.Data_zjq_bool["PV"].append(0)
						self.Data_zjq_bool["OFFMES"].append("关闭")
						self.Data_zjq_bool["ONMES"].append("打开")
						self.Data_zjq_bool["ALMENAB"].append(ALMENAB)
						self.Data_zjq_bool["NORMALVAL"].append(NORMALVAL)
						self.Data_zjq_bool["ALARMPR"].append(ALARMPR)
						self.Data_zjq_bool["SECU"].append(0)
						self.Data_zjq_bool["ALARMDELAY"].append(ALARMDELAY)
						self.Data_zjq_bool["HisKind"].append("")
						self.Data_zjq_bool["HisValue"].append("")
						self.Data_zjq_bool["LinkKind"].append(0)
						self.Data_zjq_bool["LinkDev"].append(table_data["table_name"])
						self.Data_zjq_bool["LinkDesc"].append("DO Address:"+ str(self.boolid) +" DataType:"+self.typedes)
						self.Data_zjq_bool["LinkStr"].append("DO Address:"+ str(self.boolid) +" DataType:"+self.typedes)
						self.Data_zjq_bool["Linkn0"].append(0)
						self.Data_zjq_bool["Linkn1"].append(self.boolid)
						self.Data_zjq_bool["Linkn2"].append(self.typeid)
						self.Data_zjq_bool["Linkn3"].append(0)
						self.Data_zjq_bool["Linkn4"].append(-1)
						self.Data_zjq_bool["Linkn5"].append(0)
						self.Data_zjq_bool["Linkn6"].append(0)
						self.Data_zjq_bool["LinkFmt"].append(0)
						self.Data_zjq_bool["LinkBit"].append(0)
						self.Data_zjq_bool["LinkVer"].append(1)
						self.Data_zjq_bool["LinkFlag"].append(0)
						self.Data_zjq_bool["LinkValue"].append(0)




class Drw_Tools:
	def __init__(self):
		self.drw_path=conf.f_path["drw_path"];
		self.drw_docs=conf.f_path["drw_docs"];
		self.drws=conf.exc_obj["exec_items"]["drws"]
		if not path.exists(conf.f_path["drw_docs"]): makedirs(conf.f_path["drw_docs"])
		if not self.drws:self.drws=listdir(self.drw_path)
	def zjq_tags(self):
		print("搜寻紫金桥点开始")
		for drw in self.drws:
				print("正在查找",drw)
				Data={"Tag点":[]}
				with open(self.drw_path+drw,mode="rb") as f:
					a=f.read()
				b=findall(r"([A-Z]+[0-9]?_.{1,38}?)\.PV",str(a))
				for tag in b:
					if tag not in Data["Tag点"]:
						Data["Tag点"].append(tag)
				if not Data["Tag点"]:print("没有数据");continue
				dataframe = DataFrame(Data)
				dataframe.to_csv(self.drw_docs +drw[0:-4]+ "_Tag点.csv", index=False, sep=',',encoding="gbk")
				print("完成文件",drw[0:-4]+".csv")
		print("搜寻紫金桥点结束")


